package com.ruoyi;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 需要添加依赖
 * <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
 * <dependency>
 *     <groupId>com.squareup.okhttp3</groupId>
 *     <artifactId>okhttp</artifactId>
 *     <version>4.12.0</version>
 * </dependency>
 * <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
 * <dependency>
 *     <groupId>com.alibaba.fastjson2</groupId>
 *     <artifactId>fastjson2</artifactId>
 *     <version>2.0.32</version>
 * </dependency>
 */

public class Sample {
    // 替换为你的API Key和Secret Key
    public static final String API_KEY = "0ULM7v77LK2WEY1yVnn4lxZ7";
    public static final String SECRET_KEY = "pQMHK5bh0Wj4VNQrqpdj8lenCihBXA7a";
    // 替换为你的图片URL（必须是公网可访问的）
    public static final String IMAGE_URL = "https://xit-edu.cn/2502boleapi/profile/upload/2025/08/18/tmp_e58efc85f33ae150b2b0b213be2684b5b03f1c956907621c_20250818095353A001.jpg";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient()
            .newBuilder()
            .readTimeout(300, TimeUnit.SECONDS)
            .build();

    public static void main(String[] args) throws IOException {
        // 获取访问令牌
        String accessToken = getAccessToken();
        System.out.println("获取到的access_token: " + accessToken);

        // 调用人脸检测接口获取颜值评分
        String beautyScore = getBeautyScore(accessToken);
        System.out.println("颜值评分: " + beautyScore);
    }

    /**
     * 获取访问令牌
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType,
                "grant_type=client_credentials&client_id=" + API_KEY +
                        "&client_secret=" + SECRET_KEY);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();

        // 解析JSON获取access_token
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        return jsonObject.getString("access_token");
    }

    /**
     * 调用人脸检测接口获取颜值评分
     */
    static String getBeautyScore(String accessToken) throws IOException {
        // 构造请求参数
        JSONObject requestParam = new JSONObject();
        requestParam.put("image", IMAGE_URL);          // 图片URL
        requestParam.put("image_type", "URL");         // 图片类型为URL
        requestParam.put("face_field", "beauty");      // 指定获取颜值评分

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, requestParam.toString());

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();

        // 解析响应获取颜值评分
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        if (jsonObject.getInteger("error_code") == 0) {
            JSONObject result = jsonObject.getJSONObject("result");
            if (result != null && result.getInteger("face_num") > 0) {
                return result.getJSONArray("face_list")
                        .getJSONObject(0)
                        .getString("beauty");
            } else {
                return "未检测到人脸";
            }
        } else {
            return "错误: " + jsonObject.getString("error_msg") +
                    " (错误码: " + jsonObject.getString("error_code") + ")";
        }
    }
}
